package database

import (
	"fmt"
	"log"
	"os"
	"time"

	"gitee.com/war2001/NiuMaEasyGo/global"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

// Database 数据库管理器
type Database struct {
	DB *gorm.DB
}

// Config 数据库配置
type Config struct {
	Driver            string
	Host              string
	Port              int
	Username          string
	Password          string
	Database          string
	Charset           string
	MaxIdleConns      int
	MaxOpenConns      int
	ConnMaxLifetime   int
	TablePrefix       string
	LogLevel          string
	SlowThreshold     int
	EnableAutoMigrate bool // 是否启用自动迁移
	EnableTenant      bool // 是否启用多租户
}

// New 创建数据库连接实例
func New(config *Config) (*Database, error) {
	db, err := initDatabaseConnection(config)
	if err != nil {
		return nil, err
	}

	return &Database{
		DB: db,
	}, nil
}

// initDatabaseConnection 初始化数据库连接
func initDatabaseConnection(config *Config) (*gorm.DB, error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s&parseTime=True&loc=Local",
		config.Username,
		config.Password,
		config.Host,
		config.Port,
		config.Database,
		config.Charset,
	)

	// 设置日志级别
	var logLevel logger.LogLevel
	switch config.LogLevel {
	case "silent":
		logLevel = logger.Silent
	case "error":
		logLevel = logger.Error
	case "warn":
		logLevel = logger.Warn
	case "info":
		logLevel = logger.Info
	default:
		logLevel = logger.Info
	}

	gormLogger := logger.New(
		log.New(os.Stdout, "\r\n", log.LstdFlags),
		logger.Config{
			SlowThreshold:             time.Duration(config.SlowThreshold) * time.Millisecond,
			LogLevel:                  logLevel,
			IgnoreRecordNotFoundError: true,
			Colorful:                  true,
		},
	)

	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: gormLogger,
	})
	if err != nil {
		return nil, err
	}

	// 设置连接池
	sqlDB, err := db.DB()
	if err != nil {
		return nil, err
	}
	sqlDB.SetMaxIdleConns(config.MaxIdleConns)
	sqlDB.SetMaxOpenConns(config.MaxOpenConns)
	sqlDB.SetConnMaxLifetime(time.Duration(config.ConnMaxLifetime) * time.Second)

	return db, nil
}

// InitFromGlobal 从全局配置初始化数据库
func InitFromGlobal() (*Database, error) {
	dbConfig := global.Config.Database
	config := &Config{
		Host:              dbConfig.Host,
		Port:              dbConfig.Port,
		Username:          dbConfig.Username,
		Password:          dbConfig.Password,
		Database:          dbConfig.Database,
		Charset:           dbConfig.Charset,
		MaxIdleConns:      dbConfig.MaxIdleConns,
		MaxOpenConns:      dbConfig.MaxOpenConns,
		ConnMaxLifetime:   dbConfig.ConnMaxLifetime,
		LogLevel:          dbConfig.LogLevel,
		SlowThreshold:     dbConfig.SlowThreshold,
		EnableAutoMigrate: dbConfig.EnableAutoMigrate,
	}

	return New(config)
}

// AutoMigrate 自动迁移数据库表结构
func (db *Database) AutoMigrate(models ...interface{}) error {
	return db.DB.AutoMigrate(models...)
}

// AddTenantFilter 添加租户过滤器
func (db *Database) AddTenantFilter() {
	// 添加全局回调，在查询前自动添加租户条件
	_ = db.DB.Callback().Query().Before("gorm:query").Register("tenant_filter", func(d *gorm.DB) {
		// 从上下文中获取租户ID
		tenantID, ok := d.Get("tenant_id")
		if !ok {
			return
		}

		// 检查模型是否包含TenantID字段
		if _, ok := d.Statement.Schema.FieldsByName["TenantID"]; ok {
			d.Where("tenant_id = ?", tenantID)
		}
	})
}
